package com.base.controller.api;

import com.base.helper.ApiinfoesHelper;
import com.base.po.param.NetState;
import com.base.po.voip.*;
import com.base.service.*;
import com.base.utils.GsonUtil;
import com.base.utils.Page;
import com.base.utils.Produce;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 积分结算-充值分润积分
 *
 * @author f
 */
@Controller
@RequestMapping("/pay")
public class IgRewardsController {
    @Autowired
    private UsersService usersService;
    // 用户信息
    @Autowired
    private SubscribersService subscribersService;
    @Autowired
    private ApiinfoesService apiinfoesService;
    @Autowired
    private RewardsService rewardsService;
    @Autowired
    private UserpaysService userpaysService;
    @Autowired
    private WithdrawalsService withdrawalsService;
    @Autowired
    private PayinfoesService payinfoesService;

    /**
     * 计算用户积分-充值分润积分
     *
     * @param userid 用户ID
     */
    @RequestMapping(value = "/countRewards", method = RequestMethod.POST)
    public @ResponseBody
    NetState countRewards(HttpServletRequest request, String userid) throws Exception {
        NetState netState = new NetState(); // 返回数据
        Apiinfoes apiinfoes = ApiinfoesHelper.createApiinfoes(request, "计算用户积分");
        Subscribers sub = subscribersService.selectByPrimaryKey(userid); // 用户信息
        // 如果用户信息为空 则限制执行
        if (sub == null) {
            netState.setErrorCode(NetState.ACCOUNT_ERROR);
            netState.setData("未获取到登录信息");
        } else {
            float ig = 0f;
            List<Rewards> rewardsList = rewardsService.selectByPhase(sub.getParentid(), sub.getId());
            if (rewardsList != null && rewardsList.size() > 0){
                Rewards rewards = rewardsList.get(0);
                ig = rewards.getIntegral().floatValue();
            }
            float igw = 0f;
            List<Rewards> igwList = rewardsService.selectByWithdraw(sub.getParentid(), sub.getId());
            if (igwList != null && igwList.size() > 0){
                Rewards rewards = igwList.get(0);
                igw = rewards.getIntegral().floatValue();
            }
            float ctIntegral = 0f;
            float ctAllIntegral = 0f;
            float ctUseIntegral = 0f;
            System.out.println(rewardsService.countBySelfShopNew(sub.getParentid(),sub.getId()));
            if (sub.getParentid().equals("d093179851af43dfbb1bc6639334b109")){ // 顺通提现
                ctIntegral = rewardsService.countByIntegral(sub.getParentid(), sub.getId())
                        + rewardsService.countByBonus(sub.getParentid(), sub.getId())
                        + rewardsService.countByExtra(sub.getParentid(), sub.getId())
                        + rewardsService.countBySelfShop(sub.getParentid(), sub.getId())
                        + rewardsService.countByRefund(sub.getParentid(), sub.getId())
                        - ig
                        - (withdrawalsService.countByAlready(sub.getId(), 2, 1)/0.92f - igw); // 当前用户剩余总积分 = 获得总积分 - 已经消费积分

                ctAllIntegral =  rewardsService.countByIntegral(sub.getParentid(), sub.getId())
                        + rewardsService.countByBonus(sub.getParentid(), sub.getId())
                        + rewardsService.countByExtra(sub.getParentid(), sub.getId())
                        + rewardsService.countBySelfShop(sub.getParentid(), sub.getId())
                        + rewardsService.countByRefund(sub.getParentid(), sub.getId())
                        - ig; // 获得总积分
                ctUseIntegral = withdrawalsService.countByAlready(sub.getId(), 2, 1)/0.92f - igw;// 已经消费积分
            }else if(sub.getParentid().equals("b82d635e95be4bd983acef092118785b")){ // 华韵通金提现
                ctIntegral = rewardsService.countByIntegral(sub.getParentid(), sub.getId())
                        + rewardsService.countByBonus(sub.getParentid(), sub.getId())
                        + rewardsService.countByExtra(sub.getParentid(), sub.getId())
                        - withdrawalsService.countByAlready(userid, 2, 1)/0.95f; // 当前用户剩余总积分 = 获得总积分 - 已经消费积分
            }else if(sub.getParentid().equals("58162318-deca-4442-8e38-743b7729aa5b")){
                ctIntegral = rewardsService.countByIntegral(sub.getParentid(), sub.getId())
                        + rewardsService.countByBonus(sub.getParentid(), sub.getId())
                        + rewardsService.countByExtra(sub.getParentid(), sub.getId()) // 流量卡提成
                        - withdrawalsService.countByAlready(userid, 2, null)
                        - withdrawalsService.countByAlready(userid, 4, null); // 当前用户剩余总积分 = 获得总积分 - 已经消费积分
            }else if(sub.getParentid().equals("6322af2691ba4c8884568c94cc806718")){     //西湖三宝
                ctIntegral = rewardsService.countByIntegral(sub.getParentid(), sub.getId())
                        + rewardsService.countByBonus(sub.getParentid(), sub.getId())
                        + rewardsService.countByExtra(sub.getParentid(), sub.getId()) // 流量卡提成
                        +rewardsService.countBySelfShopNew(sub.getParentid(),sub.getId())
                        - withdrawalsService.countByAlready(userid, 2, null)
                        - withdrawalsService.countByAlready(userid, 4, null); // 当前用户剩余总积分 = 获得总积分
            }else{
                ctIntegral = rewardsService.countByIntegral(sub.getParentid(), sub.getId())
                        + rewardsService.countByBonus(sub.getParentid(), sub.getId())
                        + rewardsService.countByExtra(sub.getParentid(), sub.getId())
                        - withdrawalsService.countByAlready(userid, 2, null); // 当前用户剩余总积分 = 获得总积分 - 已经消费积分
            }

            if (ctIntegral < 0f)
                ctIntegral = 0f;
            // 更新用户积分
            sub.setIgreward(ctIntegral);
            subscribersService.updateByPrimaryKeySelective(sub);
            // 积分结算成功
            netState.setErrorCode(NetState.SUCCESS_CONN);
            netState.setData("积分结算成功");
            netState.setJson(new BigDecimal(ctIntegral).setScale(2, BigDecimal.ROUND_HALF_DOWN));

            Map<String, Object> map = new HashMap<>();
            map.put("ctAllIntegral", new BigDecimal(ctAllIntegral).setScale(2, BigDecimal.ROUND_HALF_DOWN));
            map.put("ctUseIntegral", new BigDecimal(ctUseIntegral).setScale(2, BigDecimal.ROUND_HALF_DOWN));
            netState.setOtherJson(map);
        }
        apiinfoesService.insert(ApiinfoesHelper.setApiinfoes(apiinfoes, Produce.parmsToString(userid),
                GsonUtil.createJsonString(netState)));
        return netState;
    }

    /**
     * 在线充值分润积分提现支付宝申请
     *
     * @param userid 用户ID
     * @param money  提现金额
     */
    @RequestMapping(value = "/rewardsAliPay", method = {RequestMethod.POST, RequestMethod.GET})
    public @ResponseBody
    NetState rewardsAliPay(HttpServletRequest request, String userid, BigDecimal money, Integer type)
            throws Exception {
        NetState netState = new NetState(); // 返回数据对象
        Apiinfoes apiinfoes = ApiinfoesHelper.createApiinfoes(request, "提现申请"); // 调用接口信息
        Subscribers sub = subscribersService.selectByPrimaryKey(userid); // 用户信息
        if (type == null || type.equals("")){
            type = 1;
        }
        // 用户不存在或被冻结
        if (sub == null || sub.getDatastatus() == false) {
            netState.setErrorCode(NetState.ACCOUNT_ERROR);
            netState.setData("用户不存在或被冻结");
        } else {
            // 提现金额为空或者 <= 0 则提现失败
            if (money == null || money.compareTo(BigDecimal.ZERO) != 1) {
                netState.setErrorCode(NetState.PARAMS_ERROR);
                netState.setData("请输入正确的提现金额");
            } else {
                // 提现金额 > 当前积分 则提现失败
                if (money.compareTo(new BigDecimal(sub.getIgreward()).setScale(2,  BigDecimal.ROUND_HALF_UP)) == 1) {
                    netState.setErrorCode(NetState.AMOUNT_NOT_QUERY);
                    netState.setData("您当前的可提现金额不足");
                } else {
                    // 提现时查询用户是否有在线充值记录
                    if (!sub.getParentid().equals("58162318-deca-4442-8e38-743b7729aa5b") &&
                            !sub.getParentid().equals("d093179851af43dfbb1bc6639334b109") &&
                            !sub.getParentid().equals("66e9b2e1a7b848428ce0dae6aa136f6a") &&
                            !sub.getParentid().equals("e33176de98ab4581898ac3522b252cba") &&
                            payinfoesService.payinfoesByCount(
                            new Payinfoes(sub.getMobile(), sub.getParentid(), true, true, 3, "2")) <= 0) {
                        netState.setErrorCode(NetState.PARAMS_ERROR);
                        netState.setData("您还不是付费用户，现不可提现");
                    } else {
                        Userpays upays = userpaysService.selectByUserID(userid, true); // 提现信息
                        // 若没有支付宝信息 则提现失败
                        if(!sub.getParentid().equals("d093179851af43dfbb1bc6639334b109")){
                            if (upays == null || upays.getDatastatus() == false || upays.getAliaccount() == null
                                    || upays.getAliaccount().equals("")) {
                                netState.setErrorCode(NetState.PARAMS_ERROR);
                                netState.setData("请填写您的支付宝信息后进行提现");
                                return netState;
                            }
                        }
                        List<Withdrawals> hasWithdrawals = withdrawalsService.selectByStatus(2, userid, 2);
                        if (hasWithdrawals != null && hasWithdrawals.size() > 0){
                            netState.setErrorCode(NetState.AMOUNT_NOT_QUERY);
                            netState.setData("您有一笔提现正在处理，请审核通过后再进行提现");
                            return netState;
                        }

                        // 进行提现申请
                        if (sub.getParentid().equals("d093179851af43dfbb1bc6639334b109")){
                            if(sub.getIswithdraw() == 0){
                                netState.setErrorCode(NetState.PARAMS_ERROR);
                                netState.setData("您提现功能被限制，现不可提现");
                                return netState;
                            }else if(money.compareTo(new BigDecimal(100)) == -1){
                                netState.setErrorCode(NetState.AMOUNT_NOT_QUERY);
                                netState.setData("您当前的可提现金额不足100元");
                                return netState;
                            }

                            // 顺通 提现手续费8%
                            withdrawalsService.insertSelective(new Withdrawals(Produce.getUUID(), userid,
                                    Produce.getNowDate(), type, money.multiply(new BigDecimal(0.92)), 2, 2, "1"));
                        }else if(sub.getParentid().equals("b82d635e95be4bd983acef092118785b")){
                            // 华韵通金 提现手续费5%
                            withdrawalsService.insertSelective(new Withdrawals(Produce.getUUID(), userid,
                                    Produce.getNowDate(), type, money.multiply(new BigDecimal(0.95)), 2, 2, "1"));
                        }else if (sub.getParentid().equals("58162318-deca-4442-8e38-743b7729aa5b")){
                            withdrawalsService.insertSelective(new Withdrawals(Produce.getUUID(), userid,
                                    Produce.getNowDate(), type, money, 4, 2, "1"));
                        }else {
                            withdrawalsService.insertSelective(new Withdrawals(Produce.getUUID(), userid,
                                    Produce.getNowDate(), type, money, 2, 2, "1"));
                        }
                        // 提现申请成功
                        sub.setIgreward(sub.getIgreward() - money.floatValue()); // 剩余积分 = 当前积分 - 提现金额
                        subscribersService.updateByPrimaryKeySelective(sub); // 更新用户资料
                        netState.setErrorCode(NetState.SUCCESS_CONN);
                        netState.setData("提现申请成功，客服正在加急处理当中，请您留意支付宝通知");
                        netState.setJson(sub.getIgreward());
                    }
                }
            }
        }
        apiinfoesService.insert(ApiinfoesHelper.setApiinfoes(apiinfoes, Produce.parmsToString(userid, money),
                GsonUtil.createJsonString(netState)));
        return netState;
    }

    /**
     * 积分明细
     *
     * @param userid        用户ID
     * @param currentPageNo 页码
     */
    @RequestMapping(value = "/IgRewardsList", method = {RequestMethod.POST, RequestMethod.GET})
    public @ResponseBody
    NetState IgRewardsList(HttpServletRequest request, String userid, Integer currentPageNo)
            throws Exception {
        // 网络状态
        NetState netState = new NetState();
        Apiinfoes apiinfoes = ApiinfoesHelper.createApiinfoes(request, "提现记录");
        // 如果用户ID为空 则限制执行
        if (userid == null) {
            netState.setErrorCode(NetState.ACCOUNT_ERROR);
            netState.setData("用户未登录");
        } else {
            // 设置分页 获取内容
            Page page = new Page();
            if (currentPageNo != null)
                page.setCurrentPageNo(currentPageNo); // 设置当前页
            page.setRecordTotal(rewardsService.selectByCount(userid)); // 设置总条数
            List<Rewards> record = null; // 数据
            // 当前页 > 总页数 返回null
            if (currentPageNo > page.getPageTotal())
                record = null;
            else
                record = rewardsService.selectByAll(page, userid); // 查询数据
            netState.setErrorCode(NetState.SUCCESS_CONN);
            netState.setData("查询成功");
            netState.setJson(record);
        }
        apiinfoesService.insert(ApiinfoesHelper.setApiinfoes(apiinfoes, Produce.parmsToString(userid),
                GsonUtil.createJsonString(netState)));
        return netState;
    }

    /**
     * 提现记录
     *
     * @param userid        用户ID
     * @param currentPageNo 页码
     */
    @RequestMapping(value = "/recordPayList", method = {RequestMethod.POST, RequestMethod.GET})
    public @ResponseBody
    NetState recordPayList(HttpServletRequest request, String userid, Integer currentPageNo)
            throws Exception {
        // 网络状态
        NetState netState = new NetState();
        Apiinfoes apiinfoes = ApiinfoesHelper.createApiinfoes(request, "提现记录");
        // 如果用户ID为空 则限制执行
        if (userid == null) {
            netState.setErrorCode(NetState.ACCOUNT_ERROR);
            netState.setData("用户未登录");
        } else {
            // 设置分页 获取内容
            Page page = new Page();
            if (currentPageNo != null)
                page.setCurrentPageNo(currentPageNo); // 设置当前页
            page.setRecordTotal(withdrawalsService.selectByCount(userid)); // 设置总条数
            List<Withdrawals> record = null; // 数据
            // 当前页 > 总页数 返回null
            if (currentPageNo > page.getPageTotal())
                record = null;
            else
                record = withdrawalsService.selectByAll(page, userid); // 查询数据
            netState.setErrorCode(NetState.SUCCESS_CONN);
            netState.setData("查询成功");
            netState.setJson(record);
        }
        apiinfoesService.insert(ApiinfoesHelper.setApiinfoes(apiinfoes, Produce.parmsToString(userid),
                GsonUtil.createJsonString(netState)));
        return netState;
    }

    /**
     * 业绩明细
     *
     * @param userid        用户ID
     * @param level         分销等级
     * @param currentPageNo 页码
     */
    @RequestMapping(value = "/achievement", method = {RequestMethod.POST, RequestMethod.GET})
    public @ResponseBody
    NetState achievement(HttpServletRequest request, String userid, Integer currentPageNo, Integer level)
            throws Exception {
        NetState netState = new NetState();
        if (userid == null){
            netState.setErrorCode(NetState.ACCOUNT_ERROR);
            netState.setData("用户未登录");
        }else{
            Page page = new Page();
            if (currentPageNo != null)
                page.setCurrentPageNo(currentPageNo); // 设置当前页
            switch (level){
                case 1:
                    page.setRecordTotal(rewardsService.countByAllLevel1(userid)); // 设置总条数
                    break;
                case 2:
                    page.setRecordTotal(rewardsService.countByAllLevel2(userid)); // 设置总条数
                    break;
                case 3:
                    page.setRecordTotal(rewardsService.countByAllLevel3(userid)); // 设置总条数
                    break;
                default:
                    break;
            }
            List<Rewards> record = null; // 数据
            // 当前页 > 总页数 返回null
            if (currentPageNo > page.getPageTotal())
                record = null;
            else
                record = rewardsService.selectByAllLevel(page, userid, level, 1); // 查询数据
            netState.setErrorCode(NetState.SUCCESS_CONN);
            netState.setData("查询成功");
            netState.setJson(record);
        }
        return netState;
    }

    /**
     * 分销页面个人信息
     *
     * @param userid        用户ID
     */
    @RequestMapping(value = "/getUserInfo", method = {RequestMethod.POST, RequestMethod.GET})
    public @ResponseBody
    NetState getUserInfo(HttpServletRequest request, String userid)
            throws Exception {
        NetState netState = new NetState();
        if (userid == null){
            netState.setErrorCode(NetState.ACCOUNT_ERROR);
            netState.setData("用户未登录");
        }else{
            Subscribers sub = subscribersService.selectByPrimaryKey(userid);

            int shareSubs1 = rewardsService.countByAllLevel1(sub.getId());
            int shareSubs2 = rewardsService.countByAllLevel2(sub.getId());
            int shareSubs3 = rewardsService.countByAllLevel3(sub.getId());
            int level1 = 0;
            if (shareSubs1 < 3){
                level1 = 0;
            }else if (shareSubs1 >= 3 && shareSubs1 < 8){
                level1 = 1;
            }else if (shareSubs1 >= 8 && shareSubs1 < 15){
                level1 = 2;
            }else if (shareSubs1 >= 15 && shareSubs1 < 20){
                level1 = 3;
            }else if (shareSubs1 >= 20 && shareSubs1 < 30 && shareSubs2 >= 60 && shareSubs2 < 120){
                level1 = 4;
            }else if (shareSubs1 >= 30 && shareSubs1 < 40 && shareSubs2 >= 120 && shareSubs2 < 180){
                level1 = 5;
            }else if (shareSubs1 >= 40 && shareSubs1 < 60 && shareSubs2 >= 180 && shareSubs2 < 300){
                level1 = 6;
            }else if (shareSubs1 >= 60 && shareSubs1 < 80 && shareSubs2 >= 300 && shareSubs2 < 450 && shareSubs3 >= 900 && shareSubs3 < 1350){
                level1 = 7;
            }else if (shareSubs1 >= 80 && shareSubs1 < 100 &&shareSubs2 >= 450 && shareSubs2 < 600 && shareSubs3 >= 1350 && shareSubs3 < 1800){
                level1 = 8;
            }else if (shareSubs1 >= 100 && shareSubs2 >= 600 && shareSubs3 >= 1800){
                level1 = 9;
            }
            if (sub.getCbonus1level() != 0 && sub.getCbonus1level() > level1){
                level1 = sub.getCbonus1level();
            }

            Map<String, Object> subMap = new HashMap<>();
            subMap.put("username", sub.getUsername() == null ? sub.getMobile() : sub.getUsername());
            subMap.put("yearcard", sub.getIsyearcard() == 1 ? "年卡会员" : "普通会员");
            if (level1 == 0){
                subMap.put("achlevel1", "无等级");
            }else {
                subMap.put("achlevel1", "T" + level1);
            }

            netState.setErrorCode(NetState.SUCCESS_CONN);
            netState.setData("查询成功");
            netState.setJson(subMap);
        }

        return netState;
    }

    /**
     * 计算用户提成-充值分润积分
     *
     * @param userid 用户ID
     */
    @RequestMapping(value = "/countPerformanceOld", method = RequestMethod.POST)
    public @ResponseBody
    NetState countPerformance(HttpServletRequest request, String userid) throws Exception {
        NetState netState = new NetState(); // 返回数据
        Apiinfoes apiinfoes = ApiinfoesHelper.createApiinfoes(request, "计算用户积分");
        Subscribers sub = subscribersService.selectByPrimaryKey(userid); // 用户信息
        // 如果用户信息为空 则限制执行
        if (sub == null) {
            netState.setErrorCode(NetState.ACCOUNT_ERROR);
            netState.setData("未获取到登录信息");
        } else {
            Users users = usersService.selectByPrimaryKey(sub.getParentid());
            // 不进入计算的提成
            BigDecimal notPerformance = new BigDecimal(0);
            // 总团体提成比例
            BigDecimal allRatio = sub.getAllteamreratio();
            // 副特权提成比例
            BigDecimal thenRatio = sub.getTeamreratio();
            // 所有提成
            BigDecimal allPerformance = new BigDecimal(0);
            if (sub.getIsallprivilege() == 1){
                allPerformance = payinfoesService.selectPerformance(userid, sub.getAllpriopentime(), Produce.getNowDate());
            }else{
                allRatio = new BigDecimal(0);
            }
            List<Rewards> rewardsList = rewardsService.selectAllByUserID(userid);
            for (Rewards rewards : rewardsList){
                Subscribers subscribers = subscribersService.selectByPrimaryKey(rewards.getPresentid());
                if (subscribers != null && subscribers.getIsprivilege() == 1){
                    switch (rewards.getLevel()){
                        case 1:
                            notPerformance = notPerformance.add(payinfoesService.selectLv1And2Performance(subscribers.getId(), subscribers.getPriopentime(), Produce.getNowDate()));
                            break;
                        case 2:
                            notPerformance = notPerformance.add(payinfoesService.selectLv1Performance(subscribers.getId(), subscribers.getPriopentime(), Produce.getNowDate()));
                            break;
                        default:
                            break;
                    }
                }
            }

            // 副特权开启前提成
            BigDecimal allPerformanceBefore = new BigDecimal(0);
            if (sub.getIsprivilege() == 1){
                // 副特权开启前提成
                if (sub.getIsallprivilege() != null && sub.getIsallprivilege() == 1){
                    allPerformanceBefore = payinfoesService.selectPerformance(userid, sub.getAllpriopentime(), sub.getPriopentime());
                    allPerformance = allPerformanceBefore.multiply(allRatio).add(allPerformance.subtract(allPerformanceBefore)
                            .multiply(thenRatio.add(allRatio)).subtract(notPerformance.multiply(allRatio)));
                }else{
                    allPerformanceBefore = payinfoesService.selectPerformance(userid, sub.getPriopentime(), Produce.getNowDate());
                    allPerformance = allPerformanceBefore.multiply(thenRatio).subtract(notPerformance.multiply(allRatio));
                }
            }else{
                allPerformance = allPerformance.multiply(thenRatio.add(allRatio)).subtract(notPerformance.multiply(thenRatio));
            }
            float already = 0f;
            if (sub.getIsallprivilege() == 1){
                already = withdrawalsService.countByAlreadyTime(userid, 3, sub.getAllpriopentime(), Produce.getNowDate());
            }else if (sub.getIsprivilege() == 1){
                already = withdrawalsService.countByAlreadyTime(userid, 3, sub.getPriopentime(), Produce.getNowDate());
            }else if (sub.getIsallprivilege() == 1 && sub.getIsprivilege() == 1){
                if (Produce.differentDays(sub.getAllpriopentime(), sub.getPriopentime()) > 0){
                    already = withdrawalsService.countByAlreadyTime(userid, 3, sub.getAllpriopentime(), Produce.getNowDate());
                }else {
                    already = withdrawalsService.countByAlreadyTime(userid, 3, sub.getPriopentime(), Produce.getNowDate());
                }
            }
            BigDecimal ctPerformance = allPerformance.subtract(new BigDecimal(already));
            if (ctPerformance.compareTo(new BigDecimal(0)) == 0 || ctPerformance.compareTo(new BigDecimal(0)) == -1){
                ctPerformance = new BigDecimal(0);
            }

            // 更新用户积分
            sub.setPerformance(ctPerformance.setScale(0, BigDecimal.ROUND_DOWN));
            subscribersService.updateByPrimaryKeySelective(sub);
            // 积分结算成功
            netState.setErrorCode(NetState.SUCCESS_CONN);
            netState.setData("积分结算成功");
            netState.setJson(ctPerformance.setScale(0, BigDecimal.ROUND_DOWN));

            Map<String, Object> map = new HashMap<>();
            map.put("allPerformance", allPerformance);
            map.put("already", already);
            netState.setOtherJson(map);
        }
        apiinfoesService.insert(ApiinfoesHelper.setApiinfoes(apiinfoes, Produce.parmsToString(userid),
                GsonUtil.createJsonString(netState)));
        return netState;
    }

    /**
     * 计算用户提成-充值分润积分
     *
     * @param userid 用户ID
     */
    @RequestMapping(value = "/countPerformance", method = RequestMethod.POST)
    public @ResponseBody
    NetState countPerformanceNew(HttpServletRequest request, String userid) throws Exception {
        NetState netState = new NetState(); // 返回数据
        Apiinfoes apiinfoes = ApiinfoesHelper.createApiinfoes(request, "计算用户积分");
        Subscribers sub = subscribersService.selectByPrimaryKey(userid); // 用户信息
        // 如果用户信息为空 则限制执行
        if (sub == null) {
            netState.setErrorCode(NetState.ACCOUNT_ERROR);
            netState.setData("未获取到登录信息");
        } else {
            Users users = usersService.selectByPrimaryKey(sub.getParentid());
            // 总团体提成比例
            BigDecimal allRatio = sub.getAllteamreratio();
            // 副特权提成比例
            BigDecimal thenRatio = sub.getTeamreratio();
            // 所有总提成业绩
            BigDecimal allPerformance = payinfoesService.selectPerformanceTabId(userid, sub.getAllpriopentime(), Produce.getNowDate());
            // 所有副提成业绩
            BigDecimal performance = payinfoesService.selectPerformanceTabId(userid, sub.getPriopentime(), Produce.getNowDate());
            // 总特权提成
            BigDecimal chiefPerformance = new BigDecimal(0);
            // 副特权提成
            BigDecimal deputyPerformance = new BigDecimal(0);
            if (sub.getIsallprivilege() == 1){
                chiefPerformance = allPerformance.multiply(allRatio);
            }
            if (sub.getIsprivilege() == 1){
                deputyPerformance = performance.multiply(thenRatio);
            }

            float already = 0f;
            if (sub.getIsallprivilege() == 1){
                already = withdrawalsService.countByAlreadyTime(userid, 3, sub.getAllpriopentime(), Produce.getNowDate());
            }else if (sub.getIsprivilege() == 1){
                already = withdrawalsService.countByAlreadyTime(userid, 3, sub.getPriopentime(), Produce.getNowDate());
            }else if (sub.getIsallprivilege() == 1 && sub.getIsprivilege() == 1){
                if (Produce.differentDays(sub.getAllpriopentime(), sub.getPriopentime()) > 0){
                    already = withdrawalsService.countByAlreadyTime(userid, 3, sub.getAllpriopentime(), Produce.getNowDate());
                }else {
                    already = withdrawalsService.countByAlreadyTime(userid, 3, sub.getPriopentime(), Produce.getNowDate());
                }
            }
            already = already/0.92f;
            BigDecimal ctPerformance = chiefPerformance.add(deputyPerformance).subtract(new BigDecimal(already));
            if (ctPerformance.compareTo(new BigDecimal(0)) == 0 || ctPerformance.compareTo(new BigDecimal(0)) == -1){
                ctPerformance = new BigDecimal(0);
            }
            allPerformance = chiefPerformance.add(deputyPerformance);
            // 更新用户积分
            sub.setPerformance(ctPerformance.setScale(0, BigDecimal.ROUND_DOWN));
            subscribersService.updateByPrimaryKeySelective(sub);
            // 积分结算成功
            netState.setErrorCode(NetState.SUCCESS_CONN);
            netState.setData("积分结算成功");
            netState.setJson(ctPerformance.setScale(0, BigDecimal.ROUND_DOWN));

            Map<String, Object> map = new HashMap<>();
            map.put("allPerformance", allPerformance);
            map.put("already", already);
            netState.setOtherJson(map);
        }
        apiinfoesService.insert(ApiinfoesHelper.setApiinfoes(apiinfoes, Produce.parmsToString(userid),
                GsonUtil.createJsonString(netState)));
        return netState;
    }

    /**
     * 提成积分提现支付宝申请
     *
     * @param userid 用户ID
     * @param money  提现金额
     */
    @RequestMapping(value = "/performanceAliPay", method = {RequestMethod.POST, RequestMethod.GET})
    public @ResponseBody
    NetState performanceAliPay(HttpServletRequest request, String userid, BigDecimal money, Integer type)
            throws Exception {
        NetState netState = new NetState(); // 返回数据对象
        Apiinfoes apiinfoes = ApiinfoesHelper.createApiinfoes(request, "提现申请"); // 调用接口信息
        Subscribers sub = subscribersService.selectByPrimaryKey(userid); // 用户信息
        if (type == null || type.equals("")){
            type = 1;
        }
        // 用户不存在或被冻结
        if (sub == null || sub.getDatastatus() == false) {
            netState.setErrorCode(NetState.ACCOUNT_ERROR);
            netState.setData("用户不存在或被冻结");
        } else {
            // 提现金额为空或者 <= 0 则提现失败
            if (money == null || money.compareTo(BigDecimal.ZERO) != 1) {
                netState.setErrorCode(NetState.PARAMS_ERROR);
                netState.setData("请输入正确的提现金额");
            } else {
                // 提现金额 > 当前积分 则提现失败
                if (money.compareTo(sub.getPerformance()) == 1) {
                    netState.setErrorCode(NetState.AMOUNT_NOT_QUERY);
                    netState.setData("您当前的可提现金额不足");
                } else {
                    Userpays upays = userpaysService.selectByUserID(userid, true); // 提现信息
                    // 若没有支付宝信息 则提现失败
                    if (upays == null || upays.getDatastatus() == false || upays.getAliaccount() == null
                            || upays.getAliaccount().equals("")) {
                        netState.setErrorCode(NetState.PARAMS_ERROR);
                        netState.setData("请填写您的支付宝信息后进行提现");
                    } else {
                        // 进行提现申请
                        if (sub.getParentid().equals("d093179851af43dfbb1bc6639334b109")){
                            if(sub.getIswithdraw() == 0){
                                netState.setErrorCode(NetState.PARAMS_ERROR);
                                netState.setData("您提现功能被限制，现不可提现");
                            }else if(money.compareTo(new BigDecimal(100)) == -1){
                                netState.setErrorCode(NetState.AMOUNT_NOT_QUERY);
                                netState.setData("您当前的可提现金额不足100元");
                            }

                            // 顺通 提现手续费8%
                            withdrawalsService.insertSelective(new Withdrawals(Produce.getUUID(), userid,
                                    Produce.getNowDate(), type, money.multiply(new BigDecimal(0.92)), 3, 2, "1"));
                        }else{
                            withdrawalsService.insertSelective(new Withdrawals(Produce.getUUID(), userid,
                                    Produce.getNowDate(), type, money, 3, 2, "1"));
                        }
                        // 提现申请成功
                        sub.setPerformance(sub.getPerformance().subtract(money));// 剩余积分 = 当前积分 - 提现金额
                        subscribersService.updateByPrimaryKeySelective(sub); // 更新用户资料
                        netState.setErrorCode(NetState.SUCCESS_CONN);
                        netState.setData("提现申请成功，客服正在加急处理当中，请您留意支付宝通知");
                        netState.setJson(sub.getIgreward());
                    }
                }
            }
        }
        apiinfoesService.insert(ApiinfoesHelper.setApiinfoes(apiinfoes, Produce.parmsToString(userid, money),
                GsonUtil.createJsonString(netState)));
        return netState;
    }
}
